#!/usr/bin/python
# -*- coding: utf-8 -*-
import tkinter as tk
from PIL import Image, ImageTk
import GCL
import TDServer
import requests
from PIL import Image, UnidentifiedImageError
from io import BytesIO
import confdb
import dmclient
import time
import threading
import MouseCtrl

def updateConf():
    url = "https://gitee.com/tantianzuo/micro-laser-pointer/raw/master/conf.json"
    r = requests.get(url)
    j = r.json()
    serverurl = j['server']
    confdb.cfgset("serverurl", serverurl)
    confdb.cfgset("wsacodeurl", j['wsacodeurl'])
    confdb.cfgset("version", j['version'])
    print("update serverurl from:" + url)

updateConf()

def dmclientrun():
    time.sleep(0.1)
    dmclient.clientrun()


thread2 = threading.Thread(target=dmclientrun)
thread2.setDaemon(True)
thread2.start()

#20210619，不需要直接连接了
# TDServer.TDServerStart()

root = tk.Tk()
root.title("微翻页笔-电脑端")
root.eval('tk::PlaceWindow . center')
root.lift()
root.attributes('-topmost',True)
root.after_idle(root.attributes,'-topmost',False)

txtstatus = tk.StringVar()
txtstatus.set("启动中……")
status = tk.Label(root, textvariable=txtstatus)
status.pack()

def update_wsacode_img(clientid):
    # clientid = confdb.cfgget("clientid_defrwefwaef")
    if clientid:
        wsaurl = confdb.cfgget("wsacodeurl")
        # wsaurl = "http://localhost:8020/wsacode?clientid=%s"
        img_path = wsaurl % clientid
        yzmdata = requests.get(img_path)
        tempIm = BytesIO(yzmdata.content)
        img_open = Image.open(tempIm)
    else:
        img_path = "getwxacodeunlimit.jpeg"
        img_open = Image.open(img_path)
    return ImageTk.PhotoImage(img_open)


clientid = confdb.cfgget("clientid")
img_png = update_wsacode_img(clientid)
png = tk.Label(root, image=img_png)
png.pack()


txtvar = tk.StringVar()
txtvar.set("启动中……")
txt = tk.Label(root, textvariable=txtvar)
txt.pack()

btn = tk.Button(root, text="确定", command=lambda: root.quit())
btn.pack()


def uiloop():
    if not GCL.queueText.empty():
        msg = GCL.queueText.get()
        # txtvar.set(msg + "\n" + txtvar.get())
        if msg=="wsacode_update":
            try:
                clientid = confdb.cfgget("clientid")
                img_png = update_wsacode_img(clientid)
                png.configure(image=img_png)
                png.image = img_png
            except UnidentifiedImageError as e:
                print(e.strerror)

        elif msg.startswith("fullscreen"):
            ext = msg.split("_")[-1].lower()
            root.after(3000, MouseCtrl.playHotKey, ext)
        else:
            txtvar.set(msg)
    root.after(300, uiloop)


if __name__ == '__main__':
    root.after(300, uiloop)
    root.mainloop()